import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/putaway/putawaydialogscreen.dart';
import 'package:opene/ui/putaway/putawaylocationscreen.dart';
import 'package:opene/ui/putaway/putawaymodel.dart';
import 'package:opene/ui/returns/newputaway/returnsnewputataylocationscreen.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:toast/toast.dart';

class ReturnsNewPutatayScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ReturnsNewPutatayScreenPage();
  }
}

class ReturnsNewPutatayScreenPage extends StatefulWidget {
  @override
  _ReturnsNewPutatayPageState createState() => _ReturnsNewPutatayPageState();
}

class _ReturnsNewPutatayPageState extends BaseState<ReturnsNewPutatayScreen> {
  String lpnPutawayType = "P";

  List<String> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Putaway";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setLayoutBottomContentGone();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getContainerNoList();
      });
    });
  }

  void _updateRadio(int value) {
    setState(() {
      code = "";
      hint = "";
      this.type = value;
      lpnPutawayType = type == 1 ? "P" : "D";
      if (data != null) {
        data.clear();
      }
      getContainerNoList();
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 1,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          _updateRadio(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "Return_putaway",
                        style: TextStyle(color: this.type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        _updateRadio(1);
                      },
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 2,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          _updateRadio(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "Return_destroy",
                        style: TextStyle(color: this.type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        _updateRadio(2);
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  putaway(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        putaway(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan inbound lpn barcode",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 0, top: 5),
            child: Text(
              "Waiting for putaway",
              style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
          ),
          Expanded(
            child: setListView(),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        String str = data[index];
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              Utils.getStringisEmpty(str),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
            ),
            Divider(),
          ],
        );
      },
    );
  }

  ListView setListViewItem(List<PutawayLPNSkus> list) {
    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: list == null ? 0 : list.length,
      itemBuilder: (context, index) {
        PutawayLPNSkus lpnBean = list[index];
        return GestureDetector(
          onTap: () {
            putaway(lpnBean.lpn);
          },
          child: Text(
            Utils.getStringisEmpty(lpnBean.lpn),
            style: MyAppTheme.test12,
          ),
        );
      },
    );
  }

  void getContainerNoList() async {
    // 显示加载中对话框
    LoadingIndicator.show(context);
    Map<String, dynamic> map = new HashMap();
    map["processType"] = lpnPutawayType;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getReturnWaitingPutawayLpns, params: map);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : new List<String>.from(baseResponse.data) as List<String>;
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void putaway(String lpn) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["lpn"] = lpn;
    map["processType"] = lpnPutawayType;
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getReturnTallyWait, params: map);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      List<PutatayLPN> putatayLPNs = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => PutatayLPN.fromJson(userJson)).toList());

      if (putatayLPNs == null) {
        ToastContext().init(context);
        Toast.show("Nothing to deal with SKU", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if (putatayLPNs.length == 0) {
        ToastContext().init(context);
        Toast.show("Nothing to deal with SKU", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => ReturnsNewPutatayLocationScreen(lpn: lpn, lpnPutawayType: lpnPutawayType, putatayLPNs: putatayLPNs)),
      ).then((value) => {
            setState(() {
              textEditingController.text = "";
              hint = "";
            }),
            getContainerNoList()
          });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("scan inbound lpn barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    putaway(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
